﻿using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PesticideManage.API.Models;
using PesticideManage.API.Services.Files.Models;
using PesticideManage.Domain.AggregatesModel.BatchQRCodeAggregate;
using System.Net.Mime;
using System.Text;

namespace PesticideManage.API.Services.Files;
public class LocalStoreService : IStoreService
{
    private readonly IWebHostEnvironment _env;
    private readonly IConfiguration _configuration;
    private readonly ILogger<LocalStoreService> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public string CurrentName { get; } = nameof(LocalStoreService);

    public Uri BaseAddress { get; }
    public StoreSource StoreSource { get; } = StoreSource.Local;

    public LocalStoreService(IWebHostEnvironment env, IConfiguration configuration, ILogger<LocalStoreService> logger, IHttpContextAccessor httpContextAccessor)
    {
        _env = env;
        _configuration = configuration;
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;
        string? urls = _configuration["URLS"];
        string? urls2 = _configuration["ASPNETCORE_URLS"];
        var request = _httpContextAccessor.HttpContext?.Request;
        ArgumentNullException.ThrowIfNull(request, nameof(request));
        BaseAddress = new Uri($"{request.Scheme}://{request.Host.Value}");
    }

    public IActionResult GetFile(string fileName, string username)
    {
        if (string.IsNullOrEmpty(fileName))
            throw new BadHttpRequestException("文件路径错误");
        string contentRootPath = _env.ContentRootPath;
        string filePath = Path.Combine(contentRootPath, Config.FilePath, username, fileName);
        if (!System.IO.File.Exists(filePath))
        {
            throw new BadHttpRequestException("文件不存在");
        }
        //var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
        //return new FileStreamResult(fileStream, "text/plain") { FileDownloadName = fileName };

        return new PhysicalFileResult(filePath, "application/octet-stream")
        {
            FileDownloadName = fileName
        };
    }
    public async Task CreateFileAsync(IFormFile formFile)
    {
        string webRootPath = _env.WebRootPath;
        // 创建目录
        //var qrcodeFiles = Path.Combine(webRootPath, Config.FilePath);
        //Directory.CreateDirectory(qrcodeFiles);
        string filePath = Path.Combine(webRootPath, formFile.FileName);
        if (System.IO.File.Exists(filePath))
            throw new BadHttpRequestException("文件已存在");
        if (formFile.Length > 0)
        {
            using var stream = System.IO.File.Create(filePath);
            await formFile.CopyToAsync(stream);
        }
    }
    public async Task CreateFileAsync(string fileName, string userName, StringBuilder sb)
    {
        string contentRootPath = _env.ContentRootPath;
        // 创建目录
        string qrcodeFiles = Path.Combine(contentRootPath, Config.FilePath, userName);
        Directory.CreateDirectory(qrcodeFiles);

        string filePath = Path.Combine(qrcodeFiles, fileName);

        if (System.IO.File.Exists(filePath))
            throw new BadHttpRequestException("文件已存在");
        // Create a file to write to.

        using (var sw = System.IO.File.CreateText(filePath))
        {
            await sw.WriteAsync(sb.ToString());
        }

    }

    public void DeleteFile(string fileName, string username)
    {
        string contentRootPath = _env.ContentRootPath;
        string filePath = Path.Combine(contentRootPath,Config.FilePath, username, fileName);
        if (System.IO.File.Exists(filePath))
        {
            try
            {
                System.IO.File.Delete(filePath);
            }
            catch (IOException e)
            {
                _logger.LogError(e, "{Message}", e.Message);
                throw;
            }
        }

    }
}
